package com.hui.xiao.xiaohui.io;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.hui.xiao.xiaohui.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/6/4.
 */
public class CrudTest extends Activity {
    MyDatabaseHelper dbHelper;
    static List<Integer> ids = new ArrayList<>();
    static int id;
    static List<Map<String, Object>> persons = new ArrayList<>();
    TextView log;
    ListView table;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String name = msg.getData().getString("name");
            int age = msg.getData().getInt("age");
            if (msg.what == 0x123) {
                insertData(dbHelper.getReadableDatabase(), name, age);
            }
            if (msg.what == 0x124) {
                updateData(dbHelper.getReadableDatabase(), id, name, age);
            }
            loadTable();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.db_crud);
        dbHelper = new MyDatabaseHelper(this, "person.db3", 1);
        log = (TextView) findViewById(R.id.log);
        log.setText("日志~");
        table = (ListView) findViewById(R.id.grid01);
        Map<String, Object> one = new HashMap<>();
        one.put("name", "小荟");
        one.put("age", 17);
        persons.add(one);

        loadTable();

        final Button add = (Button) findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final TableLayout addForm = (TableLayout) getLayoutInflater().inflate(R.layout.db_crud_add, null);
                new AlertDialog.Builder(CrudTest.this)
                        .setIcon(R.drawable.grow)
                        .setTitle("添加用户")
                        .setView(addForm)
                        .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EditText name = (EditText) addForm.findViewById(R.id.name);
                                EditText age = (EditText) addForm.findViewById(R.id.age);
                                final Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("name", name.getText().toString());
                                bundle.putInt("age", Integer.parseInt(age.getText().toString()));
                                message.setData(bundle);
                                message.what = 0x123;
                                new Timer().schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        handler.sendMessage(message);
                                    }
                                }, 100);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
            }
        });
        Button update = (Button) findViewById(R.id.update);
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final TableLayout addForm = (TableLayout) getLayoutInflater().inflate(R.layout.db_crud_add, null);
                Map<String, Object> p = selectOne(dbHelper.getReadableDatabase(), ids.get(0));
                final EditText name = (EditText) addForm.findViewById(R.id.name);
                name.setText(p.get("name").toString());
                final EditText age = (EditText) addForm.findViewById(R.id.age);
                age.setText(p.get("age").toString());
                id = (int) p.get("id");
                new AlertDialog.Builder(CrudTest.this)
                        .setIcon(R.drawable.grow)
                        .setTitle("修改用户")
                        .setView(addForm)
                        .setPositiveButton("修改", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("name", name.getText().toString());
                                bundle.putInt("age", Integer.parseInt(age.getText().toString()));
                                message.setData(bundle);
                                message.what = 0x124;
                                new Timer().schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        handler.sendMessage(message);
                                    }
                                }, 100);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            }
        });
        Button delete = (Button) findViewById(R.id.delete);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(CrudTest.this)
                        .setTitle("删除用户")
                        .setIcon(R.drawable.grow)
                        .setMessage("确定删除用户:" + ids)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                for (int i = 0; i < ids.size(); i++) {
                                    deleteData(dbHelper.getReadableDatabase(), ids.get(i));
                                }
                                ids = new ArrayList<Integer>();
                                loadTable();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
            }
        });

    }

    void loadTable() {
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from person", new String[]{});
        persons = converCursorToList(cursor);
        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return persons.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                final Integer id = (Integer) persons.get(position).get("id");
                final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.db_crud_line, null);
                CheckBox checkBox = (CheckBox) linearLayout.findViewById(R.id.checkbox);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked && !ids.contains(id)) {
                            ids.add(id);
                        } else {
                            ids.remove(id);
                        }
                        log.setText("现在选中的:" + ids + ",id:" + id);
                    }
                });
                if (ids.contains(id)) {
                    checkBox.setChecked(true);
                }
                TextView name = (TextView) linearLayout.findViewById(R.id.name);
                name.setText(persons.get(position).get("name").toString());
                TextView age = (TextView) linearLayout.findViewById(R.id.age);
                age.setText(persons.get(position).get("age").toString());
                return linearLayout;
            }
        };
        table.setAdapter(adapter);
        log.setText("现在选中的:" + ids);
    }

    private List<Map<String, Object>> converCursorToList(Cursor cursor) {
        List<Map<String, Object>> result = new ArrayList<>();
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", cursor.getInt(0));
            map.put("name", cursor.getString(1));
            map.put("age", cursor.getInt(2));
            result.add(map);
        }
        return result;
    }

    private void insertData(SQLiteDatabase db, String name, int age) {
        db.execSQL("insert into person values(null,?,?)", new Object[]{name, age});
    }

    private void updateData(SQLiteDatabase db, int id, String name, int age) {
        db.execSQL("update person set name=?,age=? where _id =?", new Object[]{name, age, id});
    }

    private void deleteData(SQLiteDatabase db, int id) {
        db.execSQL("delete from person where _id = ?", new Object[]{id});
    }

    private Map<String, Object> selectOne(SQLiteDatabase db, int id) {
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from person where _id = ?", new String[]{String.valueOf(id)});
        if (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", cursor.getInt(0));
            map.put("name", cursor.getString(1));
            map.put("age", cursor.getInt(2));
            return map;
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
